/** *******************************************************************
 * FlexDatabaseManager
 * Copyright (c) 2008 Jonnie Spratley. All Rights Reserved.
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.accounts
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.accounts.LoginEvent;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.controls.Alert;
	import mx.managers.PopUpManager;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class LoginCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			model.interactingWithServer = true;
			
			var evt:LoginEvent = event as LoginEvent;
			var delegate:FlexDatabaseManagerDelegate = new FlexDatabaseManagerDelegate( this );
				
				if ( evt.aUser == null )
				{
					Alert.show( 'You must fill out the property fields.', 'Alert' );
					return;
				} else {
					
					//login
					delegate.checkLogin( evt.aUser );
				}
			
		}
		
		public function result( data:Object ):void
		{
			model.interactingWithServer = false;
			
			var resultObj:ResultEvent = data as ResultEvent;
			
			//Check to see if the value is true, because php isn't throwing the proper error.
			if ( resultObj.result == 1 )
			{
				//set the current user to the user that was sent
				
				//TODO: encrypt the passwords
				model.currentUser = resultObj.token.user;
				
				//set the isLoggedIn to true
				model.isLoggedIn = true;
				
				//change the view of the application
				model.workflowState = ModelLocator.MYSQL_DASHBOARD;
				
				//debug
				trace( 'successfully connected' ); 
				
			} else {
				//show an alert
				Alert.show( 'Cant connect\n Username/Password may be incorrect, try again.' );
				
				model.isLoggedIn = false;
				model.currentUser = null;
				model.workflowState = ModelLocator.MYSQL_LOGIN;
			}
		}
		
		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			
			var faultEvt:FaultEvent = fault as FaultEvent;
			
			Alert.show( faultEvt.fault.toString(), "Error");
			
			trace(faultEvt.fault.faultString);
		}
	}
}